
#include "SpeedMonitor.h"
#include "SensorMonitor.h"
#include "assert.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <signal.h>





SensorMonitor::SensorMonitor()
{
	m_fd = -1;

	initSensor();

	m_timer = new QTimer(this);
	connect(m_timer, SIGNAL(timeout()), this, SLOT(readState()));
}

SensorMonitor::~SensorMonitor()
{
	close(m_fd);
	m_timer->stop();
	delete m_timer;

	for(int i = 0; i < SENSORNOTIFY_CNT; i++)
	{
		m_sensorNotify[i] = NULL;
	}


}

void SensorMonitor::start()
{
	m_timer->start(50);
}

void SensorMonitor::stop()
{
	m_timer->stop();
}
void SensorMonitor::registerNotify(SensorNotify* sn[], int cnt, int index)
{

	assert(SENSORNOTIFY_CNT > cnt);
	for(int i = index; i < index + cnt; i++)
	{
		m_sensorNotify[i] = sn[i];
	}


}

void SensorMonitor::readState()
{
	int cnt = read(m_fd, (void*)&m_sensorState[0], sizeof(m_sensorState)); 

	assert(cnt < 1024);
	for(int i = 0;i < cnt; i++)
	{
		int id = m_sensorState[i].id;
//		printf("id = %d\n", id);
//		printf("state = %d\n", m_sensorState[i].state);
		assert(m_sensorNotify[id]);

		m_sensorNotify[id]->update(m_sensorState[i]);
	}


}


void SensorMonitor::initSensor()
{


	m_fd = open("/dev/car_sensor", 0);
	if (m_fd < 0) {
		assert(false);

	}



}



